//
//  HomeJoinVC.m
//  Ginix
//
//  Created by 冯志强 on 2025/2/24.
//

#import "HomeJoinVC.h"
#import "HomeJoinCell.h"

@interface HomeJoinVC ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic,strong) UITableView * listtView;
@property (nonatomic,strong) UILabel * infoLabel;
@property (nonatomic,strong) UIButton * enterBtn;
@property (nonatomic,strong) NSMutableArray * listArray;

@end

@implementation HomeJoinVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setSubViewLayout];
    [self requestData];
}
-(void)setSubViewLayout{
    
    self.title = @"连接您的戒指";
    self.navgationView.infoLabel.textColor = RDRGB(0x714933);
    
    [self.view addSubview:self.infoLabel];
    [_infoLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_offset(CGSizeMake(320 * FMScaleX, 40 * FMScaleX));
        make.centerX.equalTo(@0);
        make.top.mas_offset(NavHeight + 20 * FMScaleX);
    }];
    
    [self.view addSubview:self.enterBtn];
    [_enterBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_offset(CGSizeMake(330 * FMScaleX, 50 * FMScaleX));
        make.centerX.equalTo(@0);
        make.bottom.mas_offset(-kSafeAreaHeight - 50 * FMScaleX);
    }];
    [self.view addSubview:self.listtView];
    [_listtView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(@0);
        make.top.equalTo(self.infoLabel.mas_bottom).offset(10 * FMScaleX);
        make.bottom.equalTo(self.enterBtn.mas_top).offset(-10 * FMScaleX);
    }];
}

-(void)requestData{
    
    @WeakObj(self)
    [[BCLRingManager shared] getBlcConnectWithCompletion:^(BOOL state) {
        if (state) {
            [BCLRingManager.shared getCurrentDeviceWithCompletion:^(DeviceInfo * _Nullable device) {
                @StrongObj(self)
                [self.listArray addObject:device];
                [self.listtView reloadData];
            }];
        }
    }];
}

-(void)enterBtnAction{
    [[BCLRingManager shared] stopScan];
    FLodingStr(@"正在搜索请稍后");
    [[BCLRingManager shared] startScanDevicesWithCompletion:^(NSArray<DeviceInfo *> * _Nullable listArray, NSString * _Nullable str) {
        [self.listArray removeAllObjects];
        FHideLoding
        for (DeviceInfo * device in listArray) {
          if (UserInfoModel.shareInstance.userModel.isBind == 1 ){
                if ([device.macAddress isEqual:UserInfoModel.shareInstance.userModel.mac]) {
                    [self.listArray addObject:device];
                }
            }else{
                [self.listArray addObject:device];;
            }
        }
        [self.listtView reloadData];
    }];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    return self.listArray.count ;
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    
    return 50 * FMScaleX;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    HomeJoinCell * cell = [tableView dequeueReusableCellWithIdentifier:@"HomeJoinCell"];
    DeviceInfo * model = self.listArray[indexPath.row];
    if (model) {
        [cell setInfoModel:model];
    }
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [[BCLRingManager shared]stopScan];
    DeviceInfo * model = self.listArray[indexPath.row];
    NSLog(@"========%@",model.macAddress);
    
    @WeakObj(self)
    [BCLRingManager.shared getCurrentDeviceWithCompletion:^(DeviceInfo * _Nullable device) {
        @StrongObj(self)
        if (![device.uuidString isEqual:model.uuidString]) {
            FLodingStr(@"正在连接请稍后.")
            [[BCLRingManager shared] connectDeviceWithUUID:model.uuidString
                                                completion:^(BOOL success, NSString *_Nullable deviceName, NSString *_Nullable error) {
                FHideLoding
                if (success) {
                    FhudShowStr(@"连接成功");
                    if (UserInfoModel.shareInstance.userModel.isBind == 0) {
                        [self bindDeviceWithDeviceString:model.uuidString name:model.peripheralName];
                    }else{
                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                            [self.navigationController popToRootViewControllerAnimated:YES];
                        });
                    }
                } else {
                    [BDLog info:[NSString stringWithFormat:@"设备连接失败：%@", error]];
                }
            }];
        }else{
            [BCLRingManager.shared disconnect];
            [self.listArray removeAllObjects];
            [self.listtView reloadData];
        }
    }];
}


-(void)bindDeviceWithDeviceString:(NSString *)str name:(NSString *)name{
    @WeakObj(self)
    [SPNetworkingIns POST:PORT(@"user-center/api/appUser/userDevice") params:@{@"uuid":str,@"mac":self.macStr,@"deviceName":name} success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject, NSInteger code) {
        @StrongObj(self)
        FhudShowStr(@"绑定成功")
        [[BCLRingManager shared] clearRingDataWithCompletion:^(BOOL success) {
            
        }];
        [self.navigationController popToRootViewControllerAnimated:YES];

    } fail:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        
    }];
}

-(UILabel *)infoLabel{
    
    if (!_infoLabel) {
        _infoLabel = [[UILabel alloc]init];
        _infoLabel.font = Regular(14 * FMScaleX);
        _infoLabel.textColor = RDRGB(0x714933);
        _infoLabel.numberOfLines = 0;
        _infoLabel.text = @"请将您的戒指靠近手机，点击蓝牙搜索设备连接。请确保您的手机已开启蓝牙。";
    }
    return _infoLabel;
}
-(UIButton *)enterBtn{
    
    if (!_enterBtn) {
        _enterBtn = [[UIButton alloc]init];
        [_enterBtn setBackgroundImage:[UIImage imageNamed:@"Common_btn_bg"] forState:UIControlStateNormal];
        [_enterBtn setTitle:@"蓝牙搜索设备" forState:UIControlStateNormal];
        [_enterBtn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
        [_enterBtn addTarget:self action:@selector(enterBtnAction) forControlEvents:UIControlEventTouchUpInside];
        _enterBtn.titleLabel.font = Regular(14);
    }
    return _enterBtn;
}

-(UITableView *)listtView{
    
    if (!_listtView) {
        _listtView = [[UITableView alloc]init];
        _listtView.delegate = self;
        _listtView.dataSource = self;
        _listtView.showsVerticalScrollIndicator = NO;
        _listtView.showsHorizontalScrollIndicator = NO;
        _listtView.backgroundColor = UIColor.clearColor;
        _listtView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _listtView.bounces = NO;
        [_listtView registerClass:[HomeJoinCell class] forCellReuseIdentifier:@"HomeJoinCell"];
    }
    return _listtView;
}

-(NSMutableArray *)listArray{
    
    if (!_listArray) {
        _listArray = [[NSMutableArray alloc]init];
    }
    return _listArray;
}
@end
